#!/bin/bash

echo "========================================"
echo "PPH目标值节拍字段修复更新脚本"
echo "========================================"
echo

# 检查是否在正确的目录
if [ ! -d "app/frontend" ]; then
    echo "错误: 请在PPH部署包根目录下运行此脚本"
    exit 1
fi

echo "[1/5] 创建备份..."
BACKUP_DIR="app/frontend/dist.backup.$(date +%Y%m%d_%H%M%S)"
if [ -d "app/frontend/dist" ]; then
    cp -r app/frontend/dist "$BACKUP_DIR"
    echo "备份已创建: $BACKUP_DIR"
else
    echo "警告: dist目录不存在，跳过备份"
fi

echo
echo "[2/5] 停止PM2服务..."
pm2 stop all
if [ $? -ne 0 ]; then
    echo "警告: PM2停止失败，继续执行..."
fi

echo
echo "[3/5] 重新构建前端..."
cd app/frontend
npm run build
if [ $? -ne 0 ]; then
    echo "错误: 前端构建失败！"
    cd ../..
    exit 1
fi
cd ../..

echo
echo "[4/5] 重启PM2服务..."
pm2 restart all
if [ $? -ne 0 ]; then
    echo "错误: PM2重启失败！"
    exit 1
fi

echo
echo "[5/5] 检查服务状态..."
pm2 status

echo
echo "========================================"
echo "更新完成！"
echo "========================================"
echo
echo "请执行以下验证步骤："
echo "1. 打开浏览器访问PPH系统"
echo "2. 强制刷新页面 (Ctrl+Shift+R)"
echo "3. 进入'PPH目标值管理'"
echo "4. 测试节拍字段小数输入功能"
echo
echo "如果有问题，可以恢复备份："
echo "rm -rf app/frontend/dist && mv $BACKUP_DIR app/frontend/dist"
echo
